var crypto = require('crypto');
var querystring = require('querystring');
var randomString = require('random-string');
var payUtil = require('./payUtil');
var wxpay = require('./wxpay.json');

function PackageXmlMessage(pay_info){
    this.params = {
            openid: pay_info.openid,
            body: encodeURIComponent(pay_info.body),
            out_trade_no: pay_info.out_trade_no,
            total_fee: pay_info.total_fee,
            notify_url: pay_info.notify_url,
            trade_type: wxpay.trade_type,
            appid: wxpay.appid,
            mch_id: wxpay.mch_id,
            spbill_create_ip: wxpay.spbill_create_ip,
            nonce_str: payUtil.generateNonce(32)
    }
}

PackageXmlMessage.prototype.toXMLString = function(){
    var _self = this.params;
    var md5sign = _getMD5Sign(_self);
    var xml = '<xml>\
                    <openid><![CDATA['+_self.openid+']]></openid>\
                    <body><![CDATA['+_self.body+']]></body>\
                    <out_trade_no><![CDATA['+_self.out_trade_no+']]></out_trade_no>\
                    <total_fee>'+_self.total_fee+'</total_fee>\
                    <notify_url><![CDATA['+_self.notify_url+']]></notify_url>\
                    <trade_type><![CDATA['+_self.trade_type+']]></trade_type>\
                    <appid><![CDATA['+_self.appid+']]></appid>\
                    <mch_id>'+_self.mch_id+'</mch_id>\
                    <spbill_create_ip><![CDATA['+_self.spbill_create_ip+']]></spbill_create_ip>\
                    <nonce_str><![CDATA['+_self.nonce_str+']]></nonce_str>\
                    <sign><![CDATA['+md5sign+']]></sign>\
                </xml>';
    return xml;
}

function _getMD5Sign(paramObj){
    var tempObj = payUtil.ksort(paramObj);
        tempObj.key = wxpay.partner_key;
    var tempStr = decodeURIComponent(querystring.stringify(tempObj));
    return payUtil.md5(tempStr);

}

module.exports = PackageXmlMessage;